package com.ocom.webapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.MapKey;
import com.ocom.common.dto.CompanyInfoDto;
import com.ocom.common.dto.UnitsPageModifyDto;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.master.EntityCompanykeyInfo;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.RandomUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.CompanyListInfoVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.CompanyClientService;
import com.ocom.webapi.service.CompanyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Slf4j
@Service
public class CompanyServiceImpl implements CompanyService {

    @Value("${paycenter.url}")
    private String payCenterUrl;

    @Resource
    private RedisUtil redisUtil;

    //后台
    private  static Map<Integer , String> payCenter = new HashMap(){
        {
            put(0, "http://127.0.0.1:8080/wetech-admin/unfiedpay/");
            put(1, "http://192.168.84.86:35955/ocom_admin/unfiedpay/");
            put(2, "http://192.168.209.184:34063/ocom_admin/unfiedpay/");
        }
    };

    //接口
    private  static Map<Integer , String> payCenter1 = new HashMap(){
        {
            put(0, "http://127.0.0.1:8080/ocom_pay/");
            put(1, "http://192.168.3.123:32880/ocom_pay/");
            put(2, "http://192.168.185.142:33880/ocom_pay/");
        }
    };

    @Autowired
    private CompanyClientService companyClientService;

    @Override
    public Result UnitsPageOnShow(Long comId, String comName, Integer agentId, Integer page, Integer size) {
        CompanyListInfoVo companyListInfoVo =new CompanyListInfoVo();
        companyListInfoVo.setComId(comId);
        companyListInfoVo.setComName(comName);
        companyListInfoVo.setAgentId(null);
        if(agentId!=null){
            companyListInfoVo.setAgentId(agentId.longValue());
        }
        companyListInfoVo.setOnly(2);
        companyListInfoVo.setPage(page);
        companyListInfoVo.setSize(size);
        return companyClientService.GetCompanyListInfo(companyListInfoVo);
    }

    /**
     * 单位信息
     *
     * @return*/
    @Override
    public EntityCompanyInfo UnitsPageInfo(Long comId) {
        Map<String, Object> map = new HashMap<>();
        map.put("comId",comId);
        Result result = companyClientService.GetCompanyInfo(map);
        EntityCompanyInfo entityCompanyInfo= JSON.parseObject(JSON.toJSONString(result.getData()), EntityCompanyInfo.class);
//        log.info("entityCompanyInfo{{}}",entityCompanyInfo);
        Result getCompanyKeyInfoClient = companyClientService.getCompanyKeyInfo(comId,1,1);
        if (getCompanyKeyInfoClient.getCode()==200){
            JSONObject jsonObject=JSON.parseObject(JSON.toJSONString(getCompanyKeyInfoClient.getData()));
            List<EntityCompanykeyInfo> list=JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), EntityCompanykeyInfo.class);
            if (list.size()>0){
                for (EntityCompanykeyInfo entityCompanykeyInfo : list) {
                    if(entityCompanyInfo!=null){
                        entityCompanyInfo.setCommKey(entityCompanykeyInfo.getCommKey());
                    }
                    break;
                }
            }
        }
        return entityCompanyInfo;
    }



    @Override
    public EntityMngUserInfo UserPageModify(Map<String, Object> map) {

        Result result = companyClientService.UpdateMngUserInfo(map);
        EntityMngUserInfo mngUserInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityMngUserInfo.class);
        return mngUserInfo;
    }

    @Override
    public Result UnitsPageModify(CompanyInfoDto companyInfoDto) {
        return companyClientService.UpdateCompanyInfo(companyInfoDto);
    }

    /**
     * 单位信息新增
     * */
    @Override
    public Result UnitsPageAdd(UnitsPageModifyDto unitsPageModifyDto){
        Map<String, Object> map = new HashMap<>();
        YoCiUser yoCiUser= SecurityUtils.getYoCiUser();
        MapKey mapKey = new MapKey();
        //封装新增单位信息
        map.put(mapKey.getKey_comId(),unitsPageModifyDto.getComId());
        map.put(mapKey.getKey_comName(),unitsPageModifyDto.getComName());
//        map.put(mapKey.getKey_isAgent(),unitsPageModifyDto.getIsAgent());
        map.put(mapKey.getKey_agentId(),unitsPageModifyDto.getAgentId());
        map.put("isAgent",0);
        map.put(mapKey.getKey_comType(),unitsPageModifyDto.getComType());
        map.put(mapKey.getKey_comStatus(),unitsPageModifyDto.getComStatus());
        map.put(mapKey.getKey_province(),unitsPageModifyDto.getProvince());
        map.put(mapKey.getKey_city(),unitsPageModifyDto.getCity());
        map.put(mapKey.getKey_district(),unitsPageModifyDto.getDistrict());
        map.put(mapKey.getKey_contPerson(),unitsPageModifyDto.getContPerson());
        map.put(mapKey.getKey_contPhone(),unitsPageModifyDto.getContPhone());
        map.put(mapKey.getKey_contEmail(),unitsPageModifyDto.getContEmail());
        map.put(mapKey.getKey_contAddress(),unitsPageModifyDto.getContAddress());
        map.put(mapKey.getKey_remark(),unitsPageModifyDto.getRemark());
        map.put(mapKey.getKey_remark(),unitsPageModifyDto.getEndTime());
        map.put(mapKey.getKey_mjStatus(),unitsPageModifyDto.getMjStatus());
        map.put(mapKey.getKey_xfStatus(),unitsPageModifyDto.getXfStatus());
        map.put(mapKey.getKey_createUserid(),yoCiUser.getId());
        map.put("saasId",unitsPageModifyDto.getSaasId());
        map.put("isAccess",unitsPageModifyDto.getIsAccess());
        map.put("isSale",unitsPageModifyDto.getIsSale());
        map.put("payCenter",unitsPageModifyDto.getPayCenter());
        if (yoCiUser.getComId() == 1l) {
            map.put("isAgent", 1);
            map.put("agentId", 0);
            map.put("saasId",10);
        }


        Result result = companyClientService.AddCompanyInfo(map);
        if (!result.getCode().equals(200)){
            return result;
        }

        //封装初始化用户信息
        Map parseObject = JSON.parseObject(JSON.toJSONString(result.getData()), Map.class);
        Map<String, Object> map1 = new HashMap<>();
        map1.put(mapKey.getKey_comId(),parseObject.get(mapKey.getKey_comId()));
        map1.put(mapKey.getKey_userName(),unitsPageModifyDto.getUserName());
        map1.put(mapKey.getKey_password(),unitsPageModifyDto.getPassword());
        map1.put(mapKey.getKey_role(),unitsPageModifyDto.getRole());
        if (yoCiUser.getComId() == 1l) {
            map1.put(mapKey.getKey_role(),11l);
        }
        map1.put(mapKey.getKey_password(),unitsPageModifyDto.getPassword());
        map1.put(mapKey.getKey_phone(),unitsPageModifyDto.getPhone());
        map1.put(mapKey.getKey_deptId(),0);
        map1.put(mapKey.getKey_bnsId(),0);
        return companyClientService.AddCompanyAdminInfo(map1);
    }

    @Override
    public Result unitsPageBuildKey(Long comId) {
        int role= Math.toIntExact(SecurityUtils.getYoCiUser().getRole());
        if (role!=0 && role!=1 && role!=2 && role!=11){
            return ResultUtil.error(ResultEnum.Err_3028);
        }
        String commKey= RandomUtil.getRandomString(32);
        Result result =companyClientService.updateCompanyCommKey(comId,commKey);
        return result;
    }

    @Override
    public String getPayCenterUrl(Long comId, String companyId) {

        if (CommonUtil.isNull(companyId)) {
            if (!payCenterUrl.equals("dev")) {
                Map<String, Object> map = new HashMap<>();
                map.put("comId", comId);
                Result result = companyClientService.GetCompanyInfo(map);
                EntityCompanyInfo entityCompanyInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityCompanyInfo.class);
                return payCenter.get(entityCompanyInfo.getPayCenter());
            } else {
                return payCenter.get(0);
            }
        }

        Object payUrl = redisUtil.get("payCenter:#comId:"+comId+"#companyId:" + companyId);
        if (payUrl != null) return payCenter.get((Integer) payUrl);

        if (!payCenterUrl.equals("dev")) {
            if (companyId.length() > 0 && Character.isDigit(companyId.charAt(companyId.length() - 1))) {
                redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, 1 , Long.valueOf(60 * 60 * 4));
                return payCenter.get(1);
            } else {
                companyId = companyId.toUpperCase(Locale.ROOT);
                char lastChar = companyId.charAt(companyId.length() - 1);
                int indexA = (int) lastChar;
                indexA -= 63;  //A -> 2 B->3 类推
                redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, indexA , Long.valueOf(60 * 60 * 4));
                return payCenter.get(indexA);
            }

        } else {
            redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, 0 , Long.valueOf(60 * 60 * 4));
            return payCenter.get(0);
        }


    }


    @Override
    public String getPayCenterUrl1(Long comId, String companyId) {

        if (CommonUtil.isNull(companyId)) {
            if (!payCenterUrl.equals("dev")) {
                Map<String, Object> map = new HashMap<>();
                map.put("comId", comId);
                Result result = companyClientService.GetCompanyInfo(map);
                EntityCompanyInfo entityCompanyInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityCompanyInfo.class);
                return payCenter1.get(entityCompanyInfo.getPayCenter());
            } else {
                return payCenter1.get(0);
            }
        }

        Object payUrl = redisUtil.get("payCenter:#comId:"+comId+"#companyId:" + companyId+"#type:2");
        if (payUrl != null) return payCenter1.get((Integer) payUrl);

        if (!payCenterUrl.equals("dev")) {
            if (companyId.length() > 0 && Character.isDigit(companyId.charAt(companyId.length() - 1))) {
                redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, 1 , Long.valueOf(60 * 60 * 4));
                return payCenter1.get(1);
            } else {
                companyId = companyId.toUpperCase(Locale.ROOT);
                char lastChar = companyId.charAt(companyId.length() - 1);
                int indexA = (int) lastChar;
                indexA -= 63;  //A -> 2 B->3 类推
                redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, indexA , Long.valueOf(60 * 60 * 4));
                return payCenter1.get(indexA);
            }

        } else {
            redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, 0 , Long.valueOf(60 * 60 * 4));
            return payCenter1.get(0);
        }


    }

}
